<template>
  <div class="app-container">
    <!-- 顶部筛选区域 -->
    <div class="filter-section">
      <el-card class="filter-card">
        <div class="filter-content">
          <!-- 左侧时间选择区域 -->
          <div class="time-filter">
            <div class="time-type-tabs">
              <el-button 
                :type="queryParams.timeType === 'day' ? 'primary' : ''" 
                @click="handleTimeTypeChange('day')"
                class="time-tab"
              >
                日
              </el-button>
              <el-button 
                :type="queryParams.timeType === 'month' ? 'primary' : ''" 
                @click="handleTimeTypeChange('month')"
                class="time-tab"
              >
                月
              </el-button>
              <el-button 
                :type="queryParams.timeType === 'year' ? 'primary' : ''" 
                @click="handleTimeTypeChange('year')"
                class="time-tab"
              >
                年
              </el-button>
            </div>
            <div class="time-picker">
              <el-date-picker
                v-model="queryParams.selectedTime"
                :type="getDatePickerType()"
                :format="getDateFormat()"
                :value-format="getDateFormat()"
                placeholder="选择时间"
                class="date-input"
              />
            </div>
            <div class="unit-type-select">
              <span class="select-label">用能单元类型</span>
              <el-select v-model="queryParams.unitType" class="unit-select" placeholder="请选择用能单元类型">
                <el-option 
                  v-for="item in ENERGY_UNIT_TYPE_OPTIONS"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            <div class="energy-type-select">
              <span class="select-label">能源类型</span>
              <el-select v-model="queryParams.energyType" class="energy-select" placeholder="请选择能源类型">
                <el-option 
                  v-for="item in ENERGY_TYPE_OPTIONS"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            <!-- 查询按钮 -->
            <div class="query-section">
              <el-button type="primary" @click="loadConsumptionData" :loading="loading" class="query-btn">
                查询
              </el-button>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    <!-- 饼图和表格左右布局区域 -->
    <div class="content-section">
      <el-card class="content-card">
        <div class="content-layout">
          <!-- 左侧：饼图 -->
          <div class="chart-section">
            <div class="chart-container">
              <div ref="chartRef" class="pie-chart" v-loading="loading"></div>
            </div>
          </div>

          <!-- 右侧：数据表格 -->
          <div class="table-section">
            <el-table
              :data="tableData"
              v-loading="loading"
              stripe
              border
              style="width: 100%; height: 100%;"
            >
              <el-table-column prop="unitName" label="用能单元名称" align="center" />
              <el-table-column :label="getEnergyTypeLabel()" align="center">
                <el-table-column prop="consumption" :label="getConsumptionLabel()" align="right">
                  <template #default="scope">
                    <span>{{ formatNumber(scope.row.consumption) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="equivalent" label="当量(kWh)" align="right">
                  <template #default="scope">
                    <span>{{ formatNumber(scope.row.equivalent) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="ratio" label="占比(%)" align="right">
                  <template #default="scope">
                    <span class="ratio-text">{{ scope.row.ratio }}</span>
                  </template>
                </el-table-column>
              </el-table-column>
              <el-table-column prop="equivalentRatio" label="综合能耗占比(%)" align="right">
                <template #default="scope">
                  <span class="ratio-text">{{ scope.row.equivalentRatio }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick, getCurrentInstance } from 'vue'
import * as echarts from 'echarts'
import { getStatisticsGroupPie } from '@/api/stat/home'
import { 
  ENERGY_TYPE, 
  ENERGY_TYPE_OPTIONS, 
  ENERGY_UNIT_TYPE, 
  ENERGY_UNIT_TYPE_OPTIONS,
  getEnergyTypeUnit 
} from '@/utils/enums'
const { proxy } = getCurrentInstance()

// 响应式数据
const chartRef = ref(null)
const loading = ref(false)
const chartInstance = ref(null)
const tableData = ref([])

// 查询参数
const queryParams = reactive({
  timeType: 'month', // day, month 或 year
  selectedTime: new Date().getFullYear() + '-' + String(new Date().getMonth() + 1).padStart(2, '0'), // 默认当前月
  unitType: ENERGY_UNIT_TYPE.WORKSHOP, // 默认车间
  energyType: ENERGY_TYPE.ELECTRIC // 默认电
})

// 处理时间类型变化
function handleTimeTypeChange(type) {
  queryParams.timeType = type
  const now = new Date()
  
  if (type === 'day') {
    queryParams.selectedTime = now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0') + '-' + String(now.getDate()).padStart(2, '0')
  } else if (type === 'month') {
    queryParams.selectedTime = now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0')
  } else {
    queryParams.selectedTime = String(now.getFullYear())
  }
}

// 获取日期选择器类型
function getDatePickerType() {
  switch (queryParams.timeType) {
    case 'day':
      return 'date'
    case 'month':
      return 'month'
    case 'year':
      return 'year'
    default:
      return 'month'
  }
}

// 获取日期格式
function getDateFormat() {
  switch (queryParams.timeType) {
    case 'day':
      return 'YYYY-MM-DD'
    case 'month':
      return 'YYYY-MM'
    case 'year':
      return 'YYYY'
    default:
      return 'YYYY-MM'
  }
}

// 加载能耗占比数据
async function loadConsumptionData() {
  loading.value = true
  try {
    const params = {
      statTime: queryParams.selectedTime,
      groupType: queryParams.unitType,
      energyType: queryParams.energyType
    }
    
    const response = await getStatisticsGroupPie(params)
    
    if (response.data && response.data.stats && response.data.stats.length > 0) {
      // 处理API返回的数据
      const processedData = processApiData(response.data.stats)
      
      // 更新图表和表格
      updateChart(processedData.chartData)
      tableData.value = processedData.tableData
    } else {
      // 如果没有数据，清空图表和表格
      if (chartInstance.value) {
        chartInstance.value.clear()
      }
      tableData.value = []
      proxy?.$modal?.msgWarning?.('暂无数据')
    }
    
  } catch (error) {
    console.error('加载能耗占比数据失败:', error)
    proxy?.$modal?.msgError?.('加载数据失败')
    // 清空数据
    if (chartInstance.value) {
      chartInstance.value.clear()
    }
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 处理API返回的数据
function processApiData(statsData) {
  // 定义颜色数组
  const colors = ['#4fdaca', '#67C23A', '#5470c6', '#E6A23C', '#F56C6C', '#909399', '#409EFF']
  
  // 计算总量（使用sum_value）
  const totalConsumption = statsData.reduce((sum, item) => sum + (item.sum_value || 0), 0)
  
  // 处理图表数据
  const chartData = statsData.map((item, index) => {
    const value = item.sum_value || 0
    const percentage = totalConsumption > 0 ? (value / totalConsumption * 100) : 0
    
    return {
      name: item.groupName || '未知',
      value: value,
      percentage: percentage,
      color: colors[index % colors.length]
    }
  })
  
  // 处理表格数据
  const tableDataList = statsData.map((item, index) => {
    const consumption = item.sum_value || 0
    const equivalent = item.max_value || 0 // 当量使用最大值
    
    // 第一个占比：消耗量除以当量
    const consumptionRatio = equivalent > 0 ? (consumption / equivalent * 100) : 0
    
    // 第二个占比：这个用能单元的消耗量除以全部用能单元的消耗量总和
    const totalRatio = totalConsumption > 0 ? (consumption / totalConsumption * 100) : 0
    
    return {
      unitName: item.groupName || '未知',
      consumption: consumption.toFixed(2),
      equivalent: equivalent.toFixed(2), // 当量使用最大值
      ratio: consumptionRatio.toFixed(1), // 消耗量/当量
      equivalentRatio: totalRatio.toFixed(1) // 占总消耗量的比例
    }
  })
  
  // 添加合计行
  const totalEquivalent = statsData.reduce((sum, item) => sum + (item.max_value || 0), 0)
  const totalConsumptionRatio = totalEquivalent > 0 ? (totalConsumption / totalEquivalent * 100) : 0
  
  tableDataList.push({
    unitName: '合计',
    consumption: totalConsumption.toFixed(2),
    equivalent: totalEquivalent.toFixed(2),
    ratio: totalConsumptionRatio.toFixed(1), // 总消耗量/总当量
    equivalentRatio: '100' // 占总消耗量的比例
  })
  
  return {
    chartData: chartData,
    tableData: tableDataList
  }
}

// 更新饼图
function updateChart(data) {
  if (!chartRef.value) return
  
  if (!chartInstance.value) {
    chartInstance.value = echarts.init(chartRef.value)
  }
  
  // 获取当前能源类型的单位
  const unit = getEnergyTypeUnit(queryParams.energyType)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: `{a} <br/>{b}: {c}${unit} ({d}%)`
    },
    legend: {
      orient: 'horizontal',
      bottom: '5%',
      left: 'center',
      itemWidth: 14,
      itemHeight: 14,
      textStyle: {
        fontSize: 12,
        color: '#333'
      },
      formatter: function(name) {
        const item = data.find(d => d.name === name)
        return item ? `${name} ${item.percentage.toFixed(1)}%` : name
      }
    },
    series: [
      {
        name: '能耗占比',
        type: 'pie',
        radius: ['40%', '65%'],
        center: ['50%', '45%'],
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: 'outside',
          formatter: '{d}%',
          fontSize: 12,
          fontWeight: 'bold'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        labelLine: {
          show: true
        },
        data: data.map(item => ({
          value: item.value,
          name: item.name,
          itemStyle: {
            color: item.color
          }
        }))
      }
    ]
  }
  
  chartInstance.value.setOption(option)
  
  // 响应窗口大小变化
  const handleResize = () => {
    chartInstance.value?.resize()
  }
  
  window.removeEventListener('resize', handleResize)
  window.addEventListener('resize', handleResize)
}

// 格式化数字
function formatNumber(value) {
  if (!value) return '0'
  return parseFloat(value).toLocaleString()
}

// 获取消耗量列标题
function getConsumptionLabel() {
  const unit = getEnergyTypeUnit(queryParams.energyType)
  return `消耗量(${unit})`
}

// 获取能源类型标题
function getEnergyTypeLabel() {
  const option = ENERGY_TYPE_OPTIONS.find(item => item.value === queryParams.energyType)
  return option ? option.label : '电'
}

// 页面初始化
onMounted(() => {
  nextTick(() => {
    // 初始化加载数据
    loadConsumptionData()
  })
})

// 页面卸载时清理
onUnmounted(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose()
    chartInstance.value = null
  }
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background: #F1F2F5;
  height: 100%;
  display: flex;
  flex-direction: column;
}

// 筛选区域样式
.filter-section {
  margin-bottom: 20px;
  flex-shrink: 0;
  
  .filter-card {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
      .filter-content {
        padding: 16px 20px;
      
      .time-filter {
        display: flex;
        align-items: center;
        gap: 12px;
        
        .time-type-tabs {
          display: flex;
          gap: 0;
          border: 1px solid #dcdfe6;
          border-radius: 6px;
          overflow: hidden;
          
          .time-tab {
            border: none;
            border-radius: 0;
            min-width: 50px;
            height: 32px;
            font-size: 14px;
            background: #ffffff;
            color: #606266;
            
            &:not(:last-child) {
              border-right: 1px solid #dcdfe6;
            }
            
            &.el-button--primary {
              background: #4fdaca;
              color: white;
              border-color: #4fdaca;
            }
            
            &:hover:not(.el-button--primary) {
              background: #f5f7fa;
            }
          }
        }
        
        .time-picker {
          .date-input {
            width: 160px;
            height: 32px;
          }
        }
        
        .unit-type-select {
          display: flex;
          align-items: center;
          gap: 8px;
          
          .select-label {
            font-size: 14px;
            color: #606266;
            white-space: nowrap;
          }
          
          .unit-select {
            width: 140px;
            height: 32px;
          }
        }
        
        .energy-type-select {
          display: flex;
          align-items: center;
          gap: 8px;
          
          .select-label {
            font-size: 14px;
            color: #606266;
            white-space: nowrap;
          }
          
          .energy-select {
            width: 120px;
            height: 32px;
          }
        }
        
        .query-section {
          .query-btn {
            border-radius: 6px;
            height: 32px;
            background: #4fdaca;
            border-color: #4fdaca;
            
            &:hover {
              background: #32b7cb;
              border-color: #32b7cb;
            }
          }
        }
      }
    }
  }
}

// 内容区域样式（左右布局）
.content-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  
  .content-card {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    height: 100%;
    
    .content-layout {
      display: flex;
      gap: 20px;
      padding: 20px;
      height: 100%;
      
      // 左侧：饼图区域
      .chart-section {
        flex: 0 0 45%;
        display: flex;
        align-items: center;
        justify-content: center;
        border-right: 1px solid #e4e7ed;
        padding-right: 20px;
        
        .chart-container {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          
          .pie-chart {
            width: 100%;
            height: 100%;
            min-height: 400px;
          }
        }
      }
      
      // 右侧：表格区域
      .table-section {
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        
        .ratio-text {
          font-weight: 500;
          color: #2c3e50;
        }
      }
    }
  }
}

// Element Plus 组件样式覆盖
:deep(.el-card__body) {
  padding: 0;
  height: 100%;
}

:deep(.el-table) {
  border-radius: 0 !important;
  box-shadow: none !important;
  
  .el-table__header {
    background: transparent !important;
    
    tr {
      background: transparent !important;
    }
    
    th {
      background: transparent !important;
      color: #2c3e50;
      font-weight: 600;
      border-bottom: 1px solid #e4e7ed;
    }
  }
  
  .el-table__row {
    &:hover > td {
      background-color: #f5f7fa !important;
    }
    
    &:last-child {
      font-weight: 600;
      background-color: #fafafa;
      
      td {
        background-color: #fafafa !important;
        border-top: 2px solid #e4e7ed;
      }
    }
  }
  
  td {
    border-bottom: 1px solid #f0f0f0;
  }
}

:deep(.el-select) {
  .el-select__wrapper {
    border-radius: 6px;
    
    &:hover {
      border-color: #4fdaca;
    }
    
    &.is-focused {
      border-color: #4fdaca;
      box-shadow: 0 0 0 2px rgba(79, 218, 202, 0.2);
    }
  }
}

:deep(.el-date-editor) {
  .el-input__wrapper {
    border-radius: 6px;
    
    &:hover {
      border-color: #4fdaca;
    }
    
    &.is-focus {
      border-color: #4fdaca;
      box-shadow: 0 0 0 2px rgba(79, 218, 202, 0.2);
    }
  }
}

:deep(.el-button) {
  border-radius: 6px;
  
  &.el-button--primary {
    background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
    border-color: #4fdaca;
    
    &:hover {
      background: linear-gradient(135deg, #32b7cb 0%, #4fdaca 100%);
    }
  }
}

// 时间类型按钮组特殊样式
.time-type-tabs {
  :deep(.el-button) {
    border-radius: 0 !important;
    border: none !important;
    
    &.time-tab {
      background: #ffffff !important;
      color: #606266 !important;
      
      &.el-button--primary {
        background: #4fdaca !important;
        color: white !important;
      }
      
      &:hover:not(.el-button--primary) {
        background: #f5f7fa !important;
      }
      
      &:focus {
        outline: none;
        box-shadow: none;
      }
    }
  }
}

// 加载状态样式
:deep(.el-loading-mask) {
  border-radius: 8px;
}
</style>
